<template>
  <div>
    <el-dialog
      width="750px"
      :visible.sync="dialogVisible"
      class="dialog"
      title="设置规则"
    >
      <el-form
        :rules="coustomRules"
        ref="formRef"
        :model="formData"
        label-width="100px"
      >
        <el-form-item label="权益类型" prop="ptype">
          {{ ptypeMap[formData.ptype] }} &nbsp;&nbsp;&nbsp;
          <span v-if="formData.ptype == 2" style="color: #999"
            >拥有该权益，快递配送订单免运费</span
          >
          <span v-if="formData.ptype == 5" style="color: #999"
            >拥有该权益，订单会自动打标权益名称，可优先发货</span
          >
          <span v-if="formData.ptype == 6" style="color: #999"
            >拥有该权益的会员，申请售后系统将立即同意售后</span
          >
        </el-form-item>
        <div :class="hideError && 'hError'">
          <el-form-item label="权益图标" prop="icon">
            <div class="product" style="display: flex">
              <el-upload
                class="productImg__uploader product__productImg"
                :auto-upload="false"
                :on-change="addUploadBigProductImg"
                action
                :show-file-list="false"
                style="width: 100px; height: 120px"
              >
                <img
                  v-if="uploadIcon"
                  :src="uploadIcon"
                  class="product__productImg"
                  style="width: 100px; height: 120px"
                />
                <i
                  class="el-icon-plus product__productImg--uploader--icon"
                  v-if="!uploadIcon"
                  style="
                    width: 100px;
                    line-height: 100px;
                    border: 1px dotted #999;
                  "
                ></i>
              </el-upload>
              <el-button
                v-if="formData.ptype != 0"
                @click="resetIcon"
                style="height: 32px; margin: 70px 0 0 20px"
                >恢复默认</el-button
              >
            </div>
            <div class="text-info fs-12" style="color: rgba(69, 64, 60, 0.6)">
              如不设置封面卡片，则为默认官方图片
              <span style="color: red"
                >（最佳尺寸100*100，图片大小不超过150kb）</span
              >
            </div>
          </el-form-item>
        </div>
        <el-form-item label="权益名称" prop="privilegeName">
          <el-input
            style="width: 200px"
            placeholder="请输入，最多5个字符"
            :maxlength="5"
            v-model="formData.privilegeName"
          ></el-input>
        </el-form-item>
        <el-form-item label="权益说明" prop="illustrate">
          <el-input
            :rows="2"
            type="textarea"
            style="width: 200px"
            v-model="formData.illustrate"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="权益说明" prop="rules">
          <el-table
          :data="formData.rules"
          style="width: 100%">
           <el-table-column
            prop="ruleName"
            label="权益规则名称"
          >
          </el-table-column>
          <el-table-column
            prop="bei"
            label="默认倍数"
           >
          </el-table-column>
          <el-table-column
            width="120"
            label="操作">
            <template slot-scope="scope">
              <el-button @click="onEditRule(scope.row, scope.$index)" type="text">编辑</el-button>
              <el-button @click="formData.rules.splice(scope.$index, 1)"  type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button class="setupcon__item3--addnew"
          type="text"
          @click="onAddNewRule">新增权益规则
        </el-button>
        </el-form-item>-->
      </el-form>

      <span slot="footer" class="dialog--footer">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary" @click="onOk">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="ruleVisible" width="30%" title="添加权益规则">
      <el-form ref="ruleFormRef" :model="ruleForm" label-width="100px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input style="width: 160px" v-model="ruleForm.ruleName"></el-input>
        </el-form-item>
        <el-form-item label="规则名称" prop="bei">
          <el-input style="width: 160px" v-model="ruleForm.bei">
            <template slot="append">倍</template>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog--footer">
        <el-button type="primary" @click="onRuleOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref } from "vue-property-decorator";
import { upLoad } from "@/api/index";
import cloneDeep from "lodash/cloneDeep";
import {
  insertMemberCardPrivilege,
  updateMemberCardPrivilege,
} from "@/api/customer/member";
import { ptypeMapIcon } from "@/libs/const";

@Component
export default class RenewMember extends Vue {
  @Ref() readonly formRef: HTMLFormElement;

  dialogVisible = false;

  // 表单数据
  formData: any = {};

  // 上传的图片
  uploadIcon = "";

  ruleForm: any = {};

  ruleVisible = false;

  ruleType = "new";

  operateType = "new";

  operateIndex = 0;

  // 权益类型映射
  ptypeMap = {
    0: "自定义权益",
    1: "商品折扣",
    2: "物流优惠",
    3: "积分加倍",
    4: "专属客服",
    5: "优先发货",
    6: "急速售后",
  };

  hideError = false;

  // 表单的校验规则
  coustomRules = {
    privilegeName: [
      {
        required: true,
        message: "权益名称不可为空",
        // trigger: "blur",
      },
    ],
    illustrate: [
      {
        required: true,
        message: "权益说明不可为空",
        // trigger: "change",
      },
    ],
    icon: [
      {
        required: true,
        message: "权益图标不可为空",
        trigger: "change",
      },
    ],
  };

  init(formData) {
    this.formData = cloneDeep(formData || { ptype: 0 });
    this.dialogVisible = true;
    this.ruleType = formData ? "edit" : "new";
    this.uploadIcon = this.formData.icon || ptypeMapIcon[this.formData.ptype];
    this.formData.icon =
      this.formData.icon || ptypeMapIcon[this.formData.ptype];
  }

  // 上传图片
  async addUploadBigProductImg(file) {
    const whiteList = ["image/jpeg", "image/jpg", "image/png"];

    const isLt1M = file.size < 1 * 1024 * 1024;
    if (!whiteList.includes(file.raw.type)) {
      this.$message.error("上传文件只能是 JPG或PNG 格式!");
      return;
    }
    if (!isLt1M) {
      this.$message.error("上传文件大小不能超过 150kb!");
      return;
    }

    const res = await upLoad({
      file: file.raw,
    });
    this.hideError = true;
    this.formData.icon = res.data;
    this.uploadIcon = res.data;
  }

  // 恢复默认图片
  resetIcon() {
    this.uploadIcon = ptypeMapIcon[this.formData.ptype];
    this.formData.icon = ptypeMapIcon[this.formData.ptype];
  }

  onEditRule(rule, index) {
    this.ruleForm = rule;
    this.ruleVisible = true;
    this.operateType = "edit";
    this.operateIndex = index;
  }

  onAddNewRule() {
    this.ruleForm = {};
    this.ruleVisible = true;
    this.operateType = "new";
  }

  onRuleOk() {
    if (this.operateType === "edit") {
      this.formData.rules[this.operateIndex] = this.ruleForm;
    } else {
      this.formData.rules = [...(this.formData.rules || []), this.ruleForm];
    }
    this.ruleVisible = false;
  }

  // 规则设置表单确认
  async onOk() {
    this.hideError = false;
    await this.formRef.validate(() => {
      if (
        this.formData.icon &&
        this.formData.illustrate &&
        this.formData.privilegeName
      ) {
        this.hideError = true;
        const reqMap = {
          new: insertMemberCardPrivilege,
          edit: updateMemberCardPrivilege,
        };
        reqMap[this.ruleType]({
          ...this.formData,
          pType: this.formData.ptype,
          open: 1,
          allowDel: this.formData.ptype == 0 ? 1 : 0,
        }).then(() => {
          this.$message({
            type: "success",
            message: this.ruleType === "edit" ? "更新成功" : "插入成功",
          });
          this.dialogVisible = false;
          this.$emit("reFresh");
        });
      }
    });
  }

  // 点击取消弹窗
  onCancel() {
    this.$confirm("确定退出设置规则？退出后，设置规则信息将不保留。", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      this.dialogVisible = false;
    });
  }
}
</script>

<style scoped lang="scss">
@include b(hError) {
  /deep/ .el-form-item__error {
    display: none;
  }
}
</style>
